#include <stdlib.h>
#include <stdio.h>

#include "../Utils/Utils.h"
#include "../Utils/BasicTypes.h"
#include "../SparceMatrix/sparse_matrix.h"

#include "NumList.h"
#include "ListOfNumList.h"

#include "Utils.h"

//Does not delete the current num list.
ListOfNumList* SplitNumList(const NumList* toSplit, elem* splitVector)
{
	int i = 0, groupNum;
	ListOfNumList* ret = NULL, * tempList = NULL;
	NumList* groups[2] = {NULL, NULL}, *tempListValue = NULL;
	const NumList * constIter = NULL;
	elem* groupElems = NULL;
	bool retFlag = TRUE;

	NAssert(MemoryAssert(1, groupElems = (elem*)malloc(sizeof(elem)*toSplit->size)));
	
	if ((groups[0] = NewNumList()) == NULL
			|| (groups[1] = NewNumList()) == NULL
			|| (ret = NewListOfNumList()) == NULL)
	{
		DeleteNumList(groups[0]);
		DeleteNumList(groups[1]);
		free(groupElems);
		return NULL;
	}
		

		
	for (constIter = toSplit, i = 0; constIter->next != NULL; constIter = constIter->next)
		groupElems[i++] = constIter->value;
	
	for (i = toSplit->size - 1; i >= 0; i--)
	{
		if (!(retFlag = (NULL != (tempListValue = NewNumList()))))
			break;
		
		tempListValue->next = groups[groupNum = (splitVector[i] == 1 ? 0 : 1)];
		tempListValue->value = groupElems[i];
		tempListValue->size = groups[groupNum]->size + 1;
		groups[groupNum] = tempListValue;
	}
	
	if (retFlag)
	{
		for (i = 0; i < 2; i++)
		{
			if (!(retFlag = (NULL != (tempList = NewListOfNumList()))))
				break;
			tempList->next = ret;
			tempList->size = ret->size + 1;
			tempList->value = groups[splitVector[0] > 0 ? 1 - i : i];
			ret = tempList;
		}
	}
	
	free(groupElems);
	
	if (!retFlag)
	{
		DeleteNumList(groups[0]);
		DeleteNumList(groups[1]);
		DeleteListOfNumList(ret, FALSE);
		return NULL;
	}
	return ret;
}
